package com.hjw.weixun.action.oauth.sina;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.hjw.weixun.oauth.util.BareBonesBrowserLaunch;

import com.hjw.weixun.action.GenericAction;
import com.hjw.weixun.domain.User;
import com.hjw.weixun.oauth.model.OAuth;
import com.hjw.weixun.oauth.model.OAuthToken;
import com.hjw.weixun.oauth.model.SinaOauthToken;

public class SinaOauthAction extends GenericAction {
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private static final Logger logger = LoggerFactory
			.getLogger(SinaOauthAction.class);

	public static void main(String[] args) {
		SinaOauthAction soa = new SinaOauthAction();
		try {
			soa.getOauth();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public static String CONSUMER_KEY = "3607363939";
	public static String CONSUMER_SECRET = "65d07369655bb4dfd05946d99340b9ec";
	public static String CONSUMER_SECRET_URL = "http://api.t.sina.com.cn/oauth/request_token";
	public static String CONSUMER_SECRET_CALLBACK = "http://localhost:8080/WeiXun/index.jsp";
	private static Random RAND = new Random();

	public String getOauth() throws Exception {

		long timestamp = System.currentTimeMillis() / 1000;
		long nonce = timestamp + RAND.nextInt();

		/*
		 * sb.append("").append("oauth_consumer_key:\"").append(CONSUMER_KEY)
		 * .append("\",").append("oauth_signature_method:\"")
		 * .append("\"HMAC-SHA1\",").append("oauth_timestamp:\"")
		 * .append(String.valueOf(timestamp)).append("\",")
		 * .append("oauth_nonce:\"").append(String.valueOf(nonce))
		 * .append("\",").append("oauth_version:\"").append("\"1.0\"");
		 */

		HashMap<String, String> postParams = new HashMap<String, String>();
		postParams.put("oauth_consumer_key", CONSUMER_KEY);
		postParams.put("oauth_signature_method", "HMAC-SHA1");
		postParams.put("oauth_timestamp", String.valueOf(timestamp));
		postParams.put("oauth_nonce", String.valueOf(nonce));
		postParams.put("oauth_version", "1.0");
		
		postParams.put("oauth_callback", OAuth.encode(CONSUMER_SECRET_CALLBACK));
		
		String signatureBaseParams = OAuth.encodeParameters(postParams, "&",
				false);
		StringBuffer base = new StringBuffer("GET").append("&")
				.append(OAuth.encode(CONSUMER_SECRET_URL)).append("&");
		base.append(OAuth.encode(signatureBaseParams));

		String signature = OAuth.generateSignature(base.toString(),
				CONSUMER_SECRET + "&");
		logger.info("OAuth signature:" + signature);

		postParams.put("oauth_signature", signature);
		
		
		
		HttpURLConnection connection = (HttpURLConnection) new URL(
				CONSUMER_SECRET_URL).openConnection();
		
		connection.setDoInput(true);
		
		String authorization = "OAuth " + OAuth.encodeParameters(postParams, ",", true);
		
		logger.info("authorization:" + authorization);
		connection.addRequestProperty("Authorization", authorization);
		
		logger.info("Response: ");
        Map<String, List<String>> responseHeaders = connection.getHeaderFields();
        for (String key : responseHeaders.keySet()) {
            List<String> values = responseHeaders.get(key);
            for (String value : values) {
                if(null != key){
                	logger.info(key + ": " + value);
                }else{
                	logger.info(value);
                }
            }
        }

        
        InputStream is = connection.getInputStream();
        
        BufferedReader br = new BufferedReader(new InputStreamReader(is, "UTF-8"));
        
        StringBuffer buf = new StringBuffer();
        String line;
        while (null != (line = br.readLine())) {
            buf.append(line).append("\n");
        }
        logger.info(buf.toString());
        OAuthToken oAuthToken = new SinaOauthToken(buf.toString());
        
        BareBonesBrowserLaunch.openURL(oAuthToken.getAuthorizationURL());
        
		return null;

	}

	public String add() {
		User user = (User) super.getRequest().getSession().getAttribute("user");
		if (user != null) {
			String test = "aa";
			this.getRequest().setAttribute("aa", test);
			return SUCCESS;
		}
		return LOGIN;
	}

}
